from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, HttpResponse
import requests
import json


def query_weather(request):
    """
    天气视图函数
    :param request:
    :return:
    """
    city = request.GET.get('city', 'None')
    if city == 'None' or city == '':
        city = weather_by_ip()
    context = get_city_weather(city)
    print(context)
    return render(request, 'weather.html', context=context)


def weather_by_ip():
    response = requests.get("https://api.map.baidu.com/location/ip?ak=KHkVjtmfrM6NuzqxEALj0p8i1cUQot6Z")
    json_dict = json.loads(response.text)
    city = json_dict['content']['address_detail']['city']
    return city


def get_city_weather(city):
    """
    根据城市名称，获取城市天气。
    :param city_name: 城市名称
    :return:
    """
    response = requests.get("http://api.map.baidu.com/telematics/v3/weather?location={}&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?".format(city))
    json_dict = json.loads(response.text)
    print(json_dict)
    results = json_dict['results'][0]
    current_city = results['currentCity']
    weather_data = results['weather_data']
    print(weather_data)
    weather_dict = {"current_city": current_city, "weather_data": weather_data}
    return weather_dict







